<html>

<head>
    <title>批次信息配置列表</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="../../static/react/react.development.js" type="text/javascript"></script>
    <script src="../../static/react/react-dom.development.js" type="text/javascript"></script>
    <script src="../../static/react/moment-with-locales.min.js" type="text/javascript"></script>
    <script src="../../static/react/babel.min.js" type="text/javascript"></script>
    <!-- antd -->
    <link href="../../static/react/antd/antd.min.css" rel="stylesheet" type="text/css" />
    <script src="../../static/react/antd/antd-with-locales.min.js" type="text/javascript"></script>
    <!-- axios -->
    <script src="../../static/react/axios.min.js" type="text/javascript"></script>
    <script src="../../static/react/qs.js" type="text/javascript"></script>
    <script src="../../static/react/lodash.min.js" type="text/javascript"></script>
    <script src="../../static/react/request.js" type="text/javascript"></script>
    <script src="../../ffres/dict/all.js" type="text/javascript"></script>
    <link href="../../static/react/common.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        .cron-label {
            line-height: 32px;
            height: 32px;
        }
    </style>
</head>

<body>
    <div id="app"> </div>
    <script type="text/babel">
        function isEmpty(str) {
            return (!str || 0 === str.length);
        }
        class Cron extends React.Component {
            constructor(props){
                super(props)
                this.state = this.showByCron(props.value)
                this.triggerChange = function(changeValue) {
                    if (props.onChange) {
                        props.onChange(changeValue.batchCronValue)
                    }
                }.bind(this)
                this.handleChange = this.handleChange.bind(this)

            }
            showByCron(cron){
                let value = {}
                if(cron != null && cron !=""){
                    var cronList=cron.trim().split(" ");
                    if(cronList[5]=="?"){
                        if(cronList[2]=="*"&&cronList[3]=="*"&&cronList[4]=="*"){
                            if(cronList[1].indexOf("*/")==-1){
                                value.minutes = cronList[1] || ""
                                value.select_cron = "hours"
                            }else{
                                cronList[1]=cronList[1].replace("*/","");
                                value.minutes = cronList[1] || ""
                                value.select_cron = "nMinutes"
                            }
                        }else if(cronList[3]=="*"&&cronList[4]=="*"){
                            if(cronList[2].indexOf("*/")==-1){
                                value.hours = cronList[2] || ""
                                value.minutes = cronList[1] || ""
                                value.select_cron = "day"
                            }else{
                                cronList[2]=cronList[2].replace("*/","");
                                value.hours = cronList[2] || ""
                                value.minutes = cronList[1] || ""
                                value.select_cron = "nHours"
                            }
                        }else if(cronList[4]=="*"){
                            if(cronList[3].indexOf("*/")==-1){
                                value.day = cronList[3] || ""
                                value.hours = cronList[2] || ""
                                value.minutes = cronList[1] || ""
                                value.select_cron = "month"
                            }else{
                                cronList[3]=cronList[3].replace("*/","");
                                value.day = cronList[3] || ""
                                value.hours = cronList[2] || ""
                                value.minutes = cronList[1] || ""
                                value.select_cron = "nDay"
                            }
                        }
                    }else{
                        value.week = cronList[5] || ""
                        value.hours = cronList[2] || ""
                        value.minutes = cronList[1] || ""
                        value.select_cron = "week"
                    }
                }
                value.batchCronValue = cron || ""
                return value
            }
            createCron(state){
                var selectValue=state.select_cron
                var cron="";
                state.week = isEmpty(state.week) ? "" : state.week
                state.day = isEmpty(state.day) ? "" : state.day
                state.hours = isEmpty(state.hours) ? "" : state.hours
                state.minutes = isEmpty(state.minutes) ? "" : state.minutes
                if(selectValue=="week"){
                    cron="? * "+state.week;
                    cron=state.hours+" "+cron;
                    cron=state.minutes+" "+cron;
                }else if(selectValue=="month"){
                    cron="* ?";
                    cron=state.day+" "+cron;
                    cron=state.hours+" "+cron;
                    cron=state.minutes+" "+cron;
                }else if(selectValue=="nDay"){
                    cron="*/"+state.day+" * ?";
                    cron=state.hours+" "+cron;
                    cron=state.minutes+" "+cron;
                }else if(selectValue=="day"){
                    cron="* * ?";
                    cron=state.hours+" "+cron;
                    cron=state.minutes+" "+cron;
                }else if(selectValue=="nHours"){
                    cron="*/"+state.hours+" * * ?";
                    cron=state.minutes+" "+cron;
                }else if(selectValue=="hours"){
                    cron=state.minutes+" * * * ?";
                }else{
                    cron="*/"+state.minutes+" * * * ?";
                }
                cron="0 "+cron;
                return cron
            }
            handleChange(value, name) {
                const self = this
                this.setState(function(state, props){
                    // console.log("before", state, props)
                    const oldState = self.showByCron(props.value)
                    Object.assign(state, oldState)
                    state[name] = value
                    state.batchCronValue = self.createCron(state)
                    self.triggerChange(state)
                    // console.log("change", state)
                    return state
                })
            }
            createOptions(start, end) {
                let arr = []
                for (let i=start; i < end; i++) {
                    arr.push({
                        label: i,
                        value: i + ""
                    })
                }
                return arr
            }
            render(){
                // console.log(this.state)
                this.state = this.showByCron(this.props.value)
                // console.log(this.state)
                return (
                    <Row wrap={false}>
                        <Col span="4"><Select value={this.state.select_cron} onChange={val=>this.handleChange(val, 'select_cron')} disabled={this.props.disabled}>
                            <Select.Option value="day">每天</Select.Option>
                            <Select.Option value="nDay">N天</Select.Option>
                            <Select.Option value="hours">每小时</Select.Option>
                            <Select.Option value="nHours">N小时</Select.Option>
                            <Select.Option value="nMinutes">N分钟</Select.Option>
                            <Select.Option value="week">每星期</Select.Option>
                            <Select.Option value="month">每月</Select.Option>
                        </Select></Col>
                        { this.state.select_cron == 'week' && 
                        <Col flex="auto"><Select value={this.state.week} onChange={val=>this.handleChange(val, 'week')} disabled={this.props.disabled}>
                            <Select.Option value="1">周一</Select.Option>
                            <Select.Option value="2">周二</Select.Option>
                            <Select.Option value="3">周三</Select.Option>
                            <Select.Option value="4">周四</Select.Option>
                            <Select.Option value="5">周五</Select.Option>
                            <Select.Option value="6">周六</Select.Option>
                            <Select.Option value="7">周日</Select.Option>
                        </Select></Col>
                        }
                        {
                            (this.state.select_cron == 'month' || this.state.select_cron == 'nDay') && 
                            <Col flex="auto"><Select value={this.state.day} onChange={val=>this.handleChange(val, 'day')} disabled={this.props.disabled}
                                options={this.createOptions(1, 32)}>
                            </Select></Col>
                        }
                        {
                            (this.state.select_cron == 'month' || this.state.select_cron == 'nDay') && 
                            <Col ><span className="cron-label">天</span></Col>
                        }
                        {
                            !(this.state.select_cron == 'hours' || this.state.select_cron == 'nMinutes') &&
                            <Col flex="auto"><Select value={this.state.hours} onChange={val=>this.handleChange(val, 'hours')} disabled={this.props.disabled}
                                options={this.createOptions(0, 24)}>
                            </Select></Col>
                        }
                        {
                            !(this.state.select_cron == 'hours' || this.state.select_cron == 'nMinutes') &&
                            <Col ><span className="cron-label">时</span></Col>
                        }
                        <Col flex="auto"><Select value={this.state.minutes} onChange={val=>this.handleChange(val, 'minutes')} disabled={this.props.disabled}
                            options={this.createOptions(0, 60)}>
                        </Select></Col>
                        <Col ><span className="cron-label">分</span></Col>
                    </Row>
                )
            }
        }
    </script>
    <script type="text/babel">
    // 请求后台相对路径
    const baseURL = "../../"
    // ant design 组件别名引用
    const { Row, Col, Form, Input, Select, DatePicker, Button, Table, Modal, message } = antd
    // 业务组件 
    class App extends React.Component {
        constructor(props){
            super(props)
            // 在构造器中获取引用实例
            this.formRef = React.createRef()
            this.modelFormRef = React.createRef()
            // 将组件内函数绑定 this 上下文
            this.query = this.query.bind(this)
            this.reset = this.reset.bind(this)
            this.doAdd = this.doAdd.bind(this)
            this.doUpdate = this.doUpdate.bind(this)
            this.doDelete = this.doDelete.bind(this)
            this.doView = this.doView.bind(this)
            this.doConfig = this.doConfig.bind(this)
            this.statBatch = this.statBatch.bind(this)
            this.handleModelClose = this.handleModelClose.bind(this)
            this.handleModlelOk = this.handleModlelOk.bind(this)
            this.tableSelect = this.tableSelect.bind(this)
            // 初始组件数据
            this.state = {
                list: [],
                pageInfo: {
                    page: 1,
                    size: 20,
                    total: 0,
                },
                modelTitle: "",
                show: "",
                loading: false,
                opType: "", // 操作类型
                rowSelection: null,
                selectedRowKeys: []
            }
        }
        reset() {
            this.formRef.current.resetFields()
        }
        // 查询列表
        query(page){
            const self = this
            const pageInfo = this.state.pageInfo
            if (!page || typeof page != (typeof 1)) {
                pageInfo.page = 1;
            } else {
                pageInfo.page = page;
            }
            self.setState({pageInfo: pageInfo})
            API.request({
                baseURL: baseURL,
                method: "post",
                dataType: "form",
                url: "api/bat/batch/info/configs",
                data: Qs.stringify({
                    // 查询条件值通过 Form 获取
                    ...this.formRef.current.getFieldsValue(),
                    // 分页信息
                    ...this.state.pageInfo
                })
            }).then(function(data){
                const pageInfo = self.state.pageInfo 
                pageInfo.total = data.total 
                // 回写 state 中的值后  通过 setState 通知 react 更新 DOM
                self.setState({
                    list: data.rows.map(function(item, index){ return {...item, key: index}}),
                    pageInfo: pageInfo,
                })
            })

        }
        tableSelect(selectedRowKeys, selectedRows) {
            if (selectedRows && selectedRows.length > 0) {
                this.setState({
                    selectedRowKeys,
                    rowSelection: selectedRows[0]
                })
            }
        }
        doAdd() {
            this.setState({ show: true, modelTitle: "批次信息配置新增", opType: "add"});
            setTimeout(()=>this.modelFormRef.current.resetFields(), 50)
        }
        doUpdate() {
            this.setState({ show: true, modelTitle: "批次信息配置修改", opType: "update"});
            setTimeout(()=>{
                this.modelFormRef.current.setFieldsValue(this.state.rowSelection)
            }, 50)
        }
        doDelete() {
            const self = this
            if (self.state.rowSelection) {
                Modal.confirm({
                    title: '删除提示',
                    content: '你确定要删除这条记录？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk() {
                        return new Promise((resolve, reject) => {
                            API.request({
                                baseURL: baseURL,
                                method: "delete",
                                url: "api/bat/batch/info/config",
                                data: self.state.rowSelection,
                            }).then(function(data){
                                message.success("记录删除成功!")
                                resolve()
                                self.query(self.state.pageInfo.page)
                                self.setState({
                                    selectedRowKeys: []
                                })
                            })
                        });
                    },
                });
            }
        }
        doView() {
            this.setState({ show: true, modelTitle: "批次信息配置详情", opType: "view"});
            setTimeout(()=>{
                this.modelFormRef.current.setFieldsValue(this.state.rowSelection)
            }, 50)
        }
        doConfig() {
            const row = this.state.rowSelection
            if (!row) return;
            const href = 'BatchConfig.html?' + 'batchId=' + row.batchId+"&batchName="+row.batchName
            window.open(href, '_blank');
        }
        statBatch(){
            const self = this
            const row = this.state.rowSelection
            const confirmFunc = function(){
                API.request({
                    baseURL: baseURL,
                    method: "get",
                    url: "api/bat/batch/info/action/",
                    params: {
                        batchSerialNo: 'none',//由后台使用时间戳作为批次流水号
                        batchId: row.batchId,
                        batchAction: 'run'
                    }
                }).then(function(data){
                    if (data.code == '0') {
                        message.success(data.message)
                    } else {
                        message.warning(data.message)
                    }
                })
            }
            if (row.launchType == '1') {
                Modal.confirm({
                    title: '提示',
                    content: '该批次的发起方式为【定时调度】,是否确认强制手工发起批次？',
                    onOk() {
                        confirmFunc()
                    },
                });
            } else if (row.launchType == '3') {
                Modal.confirm({
                    title: '提示',
                    content: '该批次的发起方式为【集中调度】,是否确认强制手工发起批次？',
                    onOk() {
                        confirmFunc()
                    },
                });
            } else {
                Modal.confirm({
                    title: '提示',
                    content: '是否确认要手工发起批次？',
                    onOk() {
                        confirmFunc()
                    },
                });
            }
        }
        handleModelClose() {
            this.setState({
                show: false
            })
            this.modelFormRef.current.setFieldsValue({})
        }
        handleModlelOk() {
            const self = this
            const { opType } = self.state
            self.setState({
                loading: true
            })
            if (opType == "add") {
                self.modelFormRef.current.validateFields().then(function(values){
                    API.request({
                        baseURL: baseURL,
                        method: "post",
                        url: "api/bat/batch/info/config",
                        data: values
                    }).then(function(data){
                        message.success("操作成功");
                        self.setState({loading: false, show: false});
                        self.query(self.state.pageInfo.page);
                    }).catch(function(error){
                        message.warning("操作失败");
                        self.setState({loading: false});
                    })
                }).catch(function(errorInfo){
                    self.setState({loading: false})
                })
            } else if (opType == "update") {
                self.modelFormRef.current.validateFields().then(function(values){
                    API.request({
                        baseURL: baseURL,
                        method: "put",
                        url: "api/bat/batch/info/config",
                        data: values
                    }).then(function(data){
                        message.success("操作成功");
                        self.setState({loading: false, show: false});
                        self.query(self.state.pageInfo.page);
                    }).catch(function(error){
                        message.warning("操作失败");
                        self.setState({loading: false});
                    })
                }).catch(function(errorInfo){
                    self.setState({loading: false});
                })
            } else {
                self.setState({loading: false, show: false})
            }
        }
        componentDidMount() {
            this.query()
        }
        render() {
            return (
                <div style={{padding: "15px"}}>
                    {/* ref 创建 Form 实例的引用 */}
                    <Form ref={this.formRef}>
                        <Row>
                            <Col span="8">
                                <Form.Item label="批次标识" name="batchId" >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col className="btn-opt" style={{padding: "0 15px"}}>
                                <Button type="primary" onClick={this.query}>查询</Button>
                                <Button onClick={this.reset}>清空</Button>
                            </Col>
                        </Row>
                    </Form>
                    <div className="text-left btn-opt">
                        <Button type="primary" onClick={this.doAdd} >新增</Button>
                        <Button type="primary" onClick={this.doUpdate} >修改</Button>
                        <Button type="primary" onClick={this.doDelete} >删除</Button>
                        <Button type="primary" onClick={this.doView} >查看</Button>
                        <Button type="primary" onClick={this.doConfig} >批次配置</Button>
                        <Button type="primary" onClick={this.statBatch} >发起批次</Button>
                    </div>
                    { /* 
                        dataSource 为列表数组
                        onChange Table 内嵌分页 页码切换回调函数 
                        pagination Table 内嵌分页 配置 同 Pagination 组件API
                    */ }
                    <Table dataSource={this.state.list} bordered 
                        onChange={(pagination)=>this.query(pagination.current)}
                        pagination={{ position: ["bottomLeft"], 
                            current: this.state.pageInfo.page, 
                            pageSize: this.state.pageInfo.size, 
                            total: this.state.pageInfo.total }}
                        rowSelection={{
                            type: "radio",
                            selectedRowKeys: this.state.selectedRowKeys,
                            onChange: this.tableSelect
                        }}>
                        { /* Table columns 的语法糖 最终还是给 Table 传递 columns 参数 dataIndex 便是对象属性  */ }
                        <Table.Column title="批次标识" dataIndex="batchId"></Table.Column>
                        <Table.Column title="批次名称" dataIndex="batchName"></Table.Column>
                        <Table.Column title="子系统代码" dataIndex="subsCode"></Table.Column>
                        <Table.Column title="发起方式" dataIndex="launchType" 
                            render={(text, record)=>(formatter_BAT_LAUNCH_TYPE(text))}></Table.Column>
                        <Table.Column title="定时周期" dataIndex="batchCronValue"></Table.Column>
                        <Table.Column title="生效日期" dataIndex="validDate"></Table.Column>
                        <Table.Column title="任务并发数" dataIndex="equallyTaskAmount"></Table.Column>
                        <Table.Column title="是否允许重跑" dataIndex="isRunAgain" 
                            render={(text, record)=>(formatter_STD_PUB_YN(text))}></Table.Column>
                        <Table.Column title="代理节点标识" dataIndex="agentId"></Table.Column>
                        <Table.Column title="备注" dataIndex="remark"></Table.Column>
                    </Table>

                    <Modal
                        title={this.state.modelTitle}
                        visible={this.state.show}
                        onCancel={this.handleModelClose}
                        onOk={this.handleModlelOk}
                        confirmLoading={this.state.loading}
                        destroyOnClose={false}
                        keyboard={false}
                        style={{ top: 20 }}
                        okText="确定"
                        cancelText="取消"
                        width={'100%'} >
                        <Form ref={this.modelFormRef} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                            <Row>
                                <Col span="12">
                                    <Form.Item label="批次标识" name="batchId"  rules={[{ required: true, message: "请输入批次标识" }]}>
                                        <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="批次名称" name="batchName" >
                                        <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="子系统代码" name="subsCode" >
                                        <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="发起方式" name="launchType" >
                                        <Select allowClear placeholder="请选择" 
                                            options={BAT_LAUNCH_TYPE.map(function(item){
                                                return {label: item.cnname, value: item.enname}
                                            })}>
                                        </Select>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="定时周期" name="batchCronValue" >
                                        {/*<Input placeholder="请输入" disabled={this.state.opType == 'view'}/>*/}
                                        <Cron disabled={this.state.opType == 'view'}/>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="生效日期" name="validDate" >
                                        <DatePicker placeholder="请选择" />
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="任务并发数" name="equallyTaskAmount" >
                                        <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="是否允许重跑" name="isRunAgain" >
                                        <Select allowClear placeholder="请选择" 
                                            options={STD_PUB_YN.map(function(item){
                                                return {label: item.cnname, value: item.enname}
                                            })}>
                                        </Select>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="12">
                                    <Form.Item label="代理节点标识" name="agentId" >
                                        <Input placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                    </Form.Item>
                                </Col>
                        
                                <Col span="24">
                                    <Form.Item label="备注" name="remark" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                                        <Input.TextArea rows={4} placeholder="请输入" disabled={this.state.opType == 'view'}/>
                                    </Form.Item>
                                </Col>
                        
                            </Row>
                        </Form>
                    </Modal>
                </div>
            )
        }
    }
    ReactDOM.render(
        <antd.ConfigProvider locale={antd.locales.zh_CN}>
            <App />
        </antd.ConfigProvider>,
        document.getElementById('app')
    );
    </script>
</body>
</html>